accessid = '6MKOqxGiGU4AUk44';
accesskey = 'ufu7nS8kS59awNihtjSonMETLI0KLy';
host = 'http://post-test.oss-cn-hangzhou.aliyuncs.com';

g_dirname = ''
g_object_name = ''
g_object_name_type = 'random_name'
now = timestamp = Date.parse(new Date()) / 1000;

var policyText = {
	"expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
	"conditions": [
		["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
	]
};


var policyBase64 = Base64.encode(JSON.stringify(policyText));
message = policyBase64;
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {
	asBytes: true
});
var signature = Crypto.util.bytesToBase64(bytes);

function check_object_radio() {
	var tt = document.getElementsByName('myradio');
	for(var i = 0; i < tt.length; i++) {
		if(tt[i].checked) {
			g_object_name_type = tt[i].value;
			break;
		}
	}
}

function get_dirname() {
	dir = document.getElementById("dirname").value;
//	alert(dir);
	if(dir != '' && dir.indexOf('/') != dir.length - 1) {
		dir = dir + '/'
	}
	g_dirname = dir
}

function random_string(len) {　　
	len = len || 32;　　
	var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';　　
	var maxPos = chars.length;　　
	var pwd = '';　　
	for(i = 0; i < len; i++) {　　
		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

function get_suffix(filename) {
	pos = filename.lastIndexOf('.')
	suffix = ''
	if(pos != -1) {
		suffix = filename.substring(pos)
	}
	return suffix;
}

function calculate_object_name(filename) {
	suffix = get_suffix(filename)
	g_object_name = g_dirname + random_string(10) + suffix
	return ''
}


function get_uploaded_object_name(filename) {
	if(g_object_name_type == 'local_name') {
		tmp_name = g_object_name
		tmp_name = tmp_name.replace("${filename}", filename);
		return tmp_name
	} else if(g_object_name_type == 'random_name') {
		return g_object_name
	}
}

function set_upload_param(up, filename, ret) {
	g_object_name = g_dirname;
	if(filename != '') {
		suffix = get_suffix(filename)
		calculate_object_name(filename)
	}
	new_multipart_params = {
		'key': g_object_name,
		'policy': policyBase64,
		'OSSAccessKeyId': accessid,
		'success_action_status': '200', //让服务端返回200,不然，默认会返回204
		'signature': signature,
	};

	up.setOption({
		'url': host,
		'multipart_params': new_multipart_params
	});
	up.start();   
}
   
var uploader = new plupload.Uploader({
	runtimes: 'html5,flash,silverlight,html4',    
	browse_button: 'up_file_video',
	//multi_selection: false,
	container: document.getElementById('progress_bar_box'),
	flash_swf_url: '../js/lib/plupload-2.1.2/js/Moxie.swf',
	silverlight_xap_url: '../js/lib/plupload-2.1.2/js/Moxie.xap',
	url: 'http://oss.aliyuncs.com',
	init: {
		PostInit: function() {
			//上传按钮
			document.getElementById('gogo').onclick = function() {
				$('#up_file_video').attr('disabled',true);  
				$('.progress_box').removeClass('mui-hidden');
				set_upload_param(uploader, '', false);
				return false;
			};
		},

		FilesAdded: function(up, files) {
			plupload.each(files, function(file) {
				//判断上传的文件是不是MP4格式
				if(file.type != "video/mp4"){
					mui.toast('请上传mp4格式的视频文件');
					return;
				} 
				//这里处理添加视频后的本地预览
			});
		},

		BeforeUpload: function(up, file) {
			// check_object_radio();
//			get_dirname();//获取文件夹 直接随机
			set_upload_param(up, file.name, true);
		},
   
		UploadProgress: function(up, file) {
				//进度条变化  
				$('.progress_bar span').css('width', (file.percent/100) * $('.progress_bar').innerWidth());
				$('.cur_num').html(file.percent + "%");
		},
 
		FileUploaded: function(up, file, info) {
			if(info.status == 200) {
				mui.toast("上传成功");
				console.log(JSON.stringify(info)); 
//				document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name);
			} else {
				document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
			}
		},

		Error: function(up, err) {
			//			document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
			alert("上传出错");
		}
	}
});

uploader.init();